﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using elmah2.core.interfaces;
using System.Web;

namespace elmah2.StatusCodeFilter
{
  public class HttpStatusCodeFilter : IErrorFilter
  {
    public List<int> StatusCodes;

    public void Init(Dictionary<string, string> ConfigOptions)
    {
      StatusCodes = new List<int>();
      if (!ConfigOptions.ContainsKey("StatusCode"))
        throw new Exception("StatusCode Element not found for configuration");

      string[] codes = ConfigOptions["StatusCode"].ToString().Split(new char[] { ';' });

      foreach (string s in codes)
      {
        int toAdd;
        if (int.TryParse(s, out toAdd))
        {
          StatusCodes.Add(toAdd);
        }
      }
    }

    public bool FilterError(Exception ex)
    {
      if (StatusCodes == null)
        throw new Exception("Please init");

      bool result = false;
      HttpException httpexception = ex as HttpException;
      if (httpexception != null)
        result = StatusCodes.Contains(httpexception.GetHttpCode());

      return result;
    }
  }
}
